import React, { useState, useEffect } from 'react';
import axios from 'axios';
import { Layout, Table, Button, Form, Input, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import './table.css'
const { Header, Content } = Layout;

const AlgorithmManage = () => {
  const [data, setData] = useState([]);
  const [editingKey, setEditingKey] = useState('');
  const navigate = useNavigate();
  const [form] = Form.useForm();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await axios.get('http://39.106.250.42:5172/get_algorithm'); //
        const data = res.data;
        if (Array.isArray(data)) {
          setData(data.map(item => ({
            key: item.algorithm_id,
            algorithmId: item.algorithm_id,
            name: item.name,
            type: item.type,
            attribute: item.attribute,
            available: item.available,
          })));
        } else {
          console.error('Data is not an array:', data);
        }
      } catch (err) {
        console.error(err);
      }
    };

    fetchData();
  }, []);

  const isEditing = (record) => record.key === editingKey;

  const edit = (record) => {
    form.setFieldsValue({
      name: '',
      type: '',
      attribute: '',
      available: '',
      ...record,
    });
    setEditingKey(record.key);
  };

  const cancel = () => {
    setEditingKey('');
  };

  const save = async (key) => {
    try {
      const row = await form.validateFields();
      const newData = [...data];
      const index = newData.findIndex((item) => key === item.key);

      if (index > -1) {
        const item = newData[index];
        newData.splice(index, 1, { ...item, ...row });
        setData(newData);
        setEditingKey('');

        // 使用 axios.post 实时更新数据库中的数据
        await axios({
          method: "post",
          url: "http://39.106.250.42:5172/change_algorithm", //
          data: { ...item, ...row }
        }).then(res => {
          console.log(res);
        });
      } else {
        newData.push(row);
        setData(newData);
        setEditingKey('');
      }
    } catch (errInfo) {
      console.log('Validate Failed:', errInfo);
    }
  };

  const copy = (record) => {
    const newData = [...data, { ...record, key: `${record.key}_copy`, algorithmId: `${record.algorithmId}_copy` }];
    setData(newData);
    message.success('Algorithm copied successfully.');
  };

  const deleteAlgorithm = async (key) => {
    const newData = data.filter((item) => item.key !== key);
    console.log(newData[0]);
    setData(newData);
    await axios({
          method: "post",
          url: "http://39.106.250.42:5172/del_algorithm", //
          data: newData[0]
        }).then(res => {
          console.log(res);
        });
    message.success('Algorithm deleted successfully.');
  };

  const columns = [
    {
      title: '算法ID',
      dataIndex: 'algorithmId',
      editable: false,
    },
    {
      title: '名称',
      dataIndex: 'name',
      editable: true,
    },
    {
      title: '类型',
      dataIndex: 'type',
      editable: true,
    },
    {
      title: '描述',
      dataIndex: 'attribute',
      editable: true,
    },
    {
      title: 'Available',
      dataIndex: 'available',
      editable: true,
    },
    {
      title: '操作',
      dataIndex: 'operation',
      render: (_, record) => {
        const editable = isEditing(record);
        return editable ? (
          <span>
            <Button onClick={() => save(record.key)} style={{ marginRight: 8 }}>
              保存
            </Button>
            <Button onClick={cancel}>取消</Button>
          </span>
        ) : (
          <span>
            <Button onClick={() => edit(record)} style={{ marginRight: 8 }}>
              编辑
            </Button>
            {/*<Button onClick={() => copy(record)} style={{ marginRight: 8 }}>
              Copy
            </Button>*/}
            <Button onClick={() => deleteAlgorithm(record.key)} danger>
              删除
            </Button>
          </span>
        );
      },
    },
  ];

  const mergedColumns = columns.map((col) => {
    if (!col.editable) {
      return col;
    }

    return {
      ...col,
      onCell: (record) => ({
        record,
        inputType: 'text',
        dataIndex: col.dataIndex,
        title: col.title,
        editing: isEditing(record),
      }),
    };
  });

  const EditableCell = ({
    editing,
    dataIndex,
    title,
    inputType,
    record,
    index,
    children,
    ...restProps
  }) => {
    return (
      <td {...restProps}>
        {editing ? (
          <Form.Item
            name={dataIndex}
            style={{ margin: 0 }}
            rules={[
              {
                required: true,
                message: `Please Input ${title}!`,
              },
            ]}
          >
            <Input />
          </Form.Item>
        ) : (
          children
        )}
      </td>
    );
  };

  return (
    <div style={{ padding: '10px', minHeight: '100%' }} className='algorithm-manage-table'>
        <Form form={form} component={false}>
          <Table
            components={{
              body: {
                cell: EditableCell,
              },
            }}
            rowHoverable='False'
            dataSource={data}
            columns={mergedColumns}
            rowClassName="editable-row"
            pagination={{ pageSize: 10 }}
            rowKey="key"
          />
        </Form>
      </div>
  );
};

export default AlgorithmManage;